<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      :inline="true"
      v-show="showSearch"
      style="margin-top: 24px"
      @submit.native.prevent
    >
      <!-- Name搜索框 -->
      <el-form-item label="系统模块">
        <el-input
          placeholder="请输入系统模块"
          v-model="searchParams.title"
          clearable
          @keyup.enter.native="search"
        ></el-input>
      </el-form-item>

      <!-- EmergDept搜索框 -->
      <el-form-item label="类型">
        <el-select
          v-model="searchParams.TIP"
          placeholder="请选择类型"
          clearable
        >
          <el-option
            v-for="dict in typelist"
            :key="dict"
            :label="
              dict === 'insert'
                ? '添加'
                : dict === 'update'
                ? '修改'
                : dict === 'delete'
                ? '删除'
                : ''
            "
            :value="dict"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- EmergTitle搜索框 -->
      <el-form-item label="状态">
        <el-select
          placeholder="请选择状态"
          v-model="searchParams.message"
          clearable
        >
          <el-option
            v-for="dict in statelist"
            :key="dict"
            :label="dict === 'success' ? '成功' : '失败'"
            :value="dict"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="日期">
        <el-date-picker v-model="searchParams.timestamp" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="getFormattedDates">
        </el-date-picker>
      </el-form-item> -->
      <!-- 搜索按钮 -->
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['monitor:operlog:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['monitor:operlog:remove']"
          >清空</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['monitor:operlog:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="paginatedItems"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="日志编号" align="center" prop="id" />
      <el-table-column
        label="系统模块"
        align="center"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作类型" align="center" prop="TIP">
        <template slot-scope="scope">
          <el-tag :type="getTypeColor(scope.row.TIP)">{{
            getDisplayText(scope.row.TIP)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作状态" align="center" prop="message">
        <template slot-scope="scope">
          <el-tag :type="StatusColor(scope.row.message)">{{
            StatuText(scope.row.message)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作日期"
        align="center"
        prop="timestamp"
        width="160"
        sortable="custom"
        :sortable="true"
        :sort-orders="['descending', 'ascending']"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消耗时间" align="center" prop="costTime">
        <template slot-scope="scope">
          <span>{{ scope.row.costTime }}毫秒</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row, scope.index)"
            v-hasPermi="['monitor:operlog:query']"
            >详细</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="currentPage = $event"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      style="margin-top;: 2%"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredItems.length"
    >
    </el-pagination>
    <!-- 操作日志详细 -->
    <el-dialog
      title="操作日志详细"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作模块："
              >{{ form.title }} / {{ getDisplayText(form.TIP) }}</el-form-item
            >
          </el-col>
          <el-col :span="6">
            <el-form-item label="请求方式"
              >{{ form.TIP }}
            </el-form-item></el-col
          >
          <el-col :span="24">
            <el-form-item label="请求参数：">{{ form.SQL }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="返回参数："
              >{"message":"{{ form.message }}","code":{{
                form.code
              }}}</el-form-item
            >
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作状态：">
              <div v-if="form.code === '1'">正常</div>
              <div v-else-if="form.code === '-1'">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="消耗时间">毫秒</el-form-item></el-col
          >
          <el-col :span="10">
            <el-form-item label="操作时间：">{{
              parseTime(form.timestamp)
            }}</el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="异常信息：" v-if="form.status === '-1'">{{
              form.message
            }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getLists,
  insertData,
  deletelist,
  ALLdeletelist,
} from "../../api/Genericmethods/GeneralQuery.js";
export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      items: [], // 存储所有数据
      filteredItems: [], // 存储搜索结果
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的数据数量
      searchParams: {
        // 存储搜索参数
        TIP: "",
        message: "",
        title: "",
        timestamp: null,
      },
      // 表单参数
      form: {},
      typelist: [], //类型
      statelist: [], //状态
      CompanyJobList: [], //公司职务
      // 修改获取到的数组
      Originalarray: [],
      formattedStartDate: "",
      formattedEndDate: "",
    };
  },
  created() {
    this.getList();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  methods: {
    getFormattedDates() {
      const startDate = new Date(this.searchParams.timestamp[0]);
      const endDate = new Date(this.searchParams.timestamp[1]);

      const startFormatted = startDate.getTime();
      const endFormatted = endDate.getTime();

      console.log("开始时间:", startFormatted);
      console.log("结束时间:", endFormatted);
    },
    // 类型标签的颜色
    getTypeColor(type) {
      if (type === "insert") {
        return "info"; // 返回 info 类型的颜色
      } else if (type === "update") {
        return "info"; // 返回 info 类型的颜色
      } else if (type === "delete") {
        return "danger"; // 返回 danger 类型的颜色
      } else {
        return ""; // 默认情况下返回空字符串，不设置特定的颜色
      }
    },
    // 类型标签文字的显示
    getDisplayText(TIP) {
      if (TIP === "insert") {
        return "添加"; // 如果 scope.row.TIP 为 "insert"，返回 "添加"
      } else if (TIP === "update") {
        return "修改"; // 如果 scope.row.TIP 为 "update"，返回 "修改"
      } else if (TIP === "delete") {
        return "删除"; // 如果 scope.row.TIP 为 "delete"，返回 "删除"
      } else {
        return ""; // 默认情况下返回空字符串，不显示任何文字
      }
    },
    // 状态标签颜色显示
    StatusColor(states) {
      if (states === "success") {
        return "";
      } else {
        return "danger";
      }
    },
    // 状态标签文字的显示
    StatuText(states) {
      if (states === "success") {
        return "成功";
      } else {
        return "失败";
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      getLists("OperationLogList")
        .then((data) => {
          // 按照id倒序排序
          data.sort((a, b) => b.id - a.id);
          // console.log(data, "5555");
          this.items = data;
          this.filteredItems = data;
          this.loading = false;
          // 类型下拉框
          const companyTitles = new Set(data.map((item) => item.TIP));
          this.typelist = Array.from(companyTitles);
          // 状态下拉框
          const EmergDepts = new Set(data.map((item) => item.message));
          this.statelist = Array.from(EmergDepts);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 搜索
    search() {
      const { TIP, message, title } = this.searchParams;

      // 使用过滤方法进行搜索
      this.filteredItems = this.items.filter((item) => {
        const isMatch = (value, keyword) => {
          if (value !== null) {
            return value.toLowerCase().includes(keyword.toLowerCase());
          }
        };

        return (
          isMatch(item.TIP, TIP) &&
          isMatch(item.message, message) &&
          isMatch(item.title, title)
        );
      });

      this.currentPage = 1; // 搜索后将当前页码重置为第一页
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          const operIds = row.operId || this.ids;
          // 使用循环来逐个发送删除请求
          operIds.forEach((id) => {
            const data = `"id" ='${id}'`;
            deletelist("OperationLogList", data)
              .then((res) => {
                if (res.data.code === 1) {
                  this.getList();
                  this.$message.success("删除成功");
                } else {
                  this.$message.error(res.data.message);
                }
              })
              .catch((error) => {
                console.log(error);
              });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /** 清空按钮操作 */
    handleClean() {
      this.$confirm("是否要清空所有数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          ALLdeletelist("OperationLogList")
            .then((res) => {
              if (res.data.code === 1) {
                this.getList();
                this.$modal.msgSuccess("清空成功");
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消清空",
          });
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
  computed: {
    paginatedItems() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.filteredItems.slice(startIndex, endIndex);
    },
    totalPages() {
      return Math.ceil(this.filteredItems.length / this.pageSize);
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep.el-pagination {
  margin-top: 2%;
}
</style>
